<template>
  <page-header-wrapper>
    <a-card :bordered="false">
      <div class="table-page-search-wrapper">
        <a-form
          layout="inline"
          :label-col="{ offset: 1 }">
          <a-row :gutter="24">
            <a-col
              :md="6"
              :sm="24">
              <a-form-item label="姓名">
                <a-input
                  v-model="queryParam.name"
                  placeholder="请输入员工姓名" />
              </a-form-item>
            </a-col>
            <a-col
              :md="6"
              :sm="16">
              <a-form-item label="入职日期">
                <a-range-picker
                  :placeholder="['开始日期','结束日期']"
                  valueFormat="YYYY-MM-DD 00:00:00"
                  v-model="queryParam.entryDate" />
              </a-form-item>
            </a-col>
            <a-col
              :md="6"
              :sm="16">
              <a-form-item label="部门">
                <a-input
                  v-model="queryParam.department"
                  placeholder="请输入部门" />
              </a-form-item>
            </a-col>
            <a-col
              :md="6"
              :sm="16">
              <a-form-item label="岗位">
                <a-input
                  v-model="queryParam.jobs"
                  placeholder="请输入员工岗位" />
              </a-form-item>
            </a-col>
            <a-col
              :md="6"
              :sm="16">
              <a-form-item label="状态">
                <a-select
                  v-model="queryParam.status"
                  placeholder="请选择账号状态"
                  default-value="0">
                  <a-select-option value="0">禁用</a-select-option>
                  <a-select-option value="1">启用</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col
              :md="6"
              :sm="16">
              <span
                class="table-page-search-submitButtons"
                :style="{ overflow: 'hidden' }">
                <a-button
                  type="primary"
                  v-if="list"
                  @click="searchStaff">查询</a-button>
                <a-button
                  style="margin-left: 8px"
                  v-if="list"
                  @click="() => {this.queryParam = {};this.$refs.table.refresh() }">重置</a-button>
              </span>
            </a-col>
          </a-row>
        </a-form>
      </div>

      <div class="table-operator" v-if="save">
        <a-button
          type="primary"
          icon="plus"
          @click="handleAdd">新建</a-button>
      </div>
      <div>
        <a-row :gutter="48">
          <a-col
            :md="24"
            :sm="24">
            <s-table
              ref="table"
              size="default"
              rowKey="userId"
              :columns="columns"
              :data="loadData"
              showPagination="auto"
              :customRow="tableCustomRow">
              <span
                slot="serial"
                slot-scope="text, record, index">
                {{ index + 1 }}
              </span>
              <span
                slot="entryDate"
                slot-scope="text, record">
                {{ record.entryDate.split(' ')[0] }}
              </span>
              <span
                slot="status"
                slot-scope="text">
                <a-badge
                  :status="text | statusTypeFilter"
                  :text="text | statusFilter" />
              </span>
              <span
                slot="action"
                slot-scope="text, record">
                <template>
                  <a
                    @click="deleteUser(record.userId)"
                    v-if="record.status === 1 && status && record.userId !== 1"
                  >禁用用户</a>
                  <a
                    v-if="record.status === 0 && status && record.userId !== 1"
                    @click="startUser(record.userId)"
                  >启用用户</a>
                  <a-divider type="vertical" v-if="status" />
                  <a v-if="update" @click="handleEdit(record)">配置</a>
                  <a-divider type="vertical" />
                  <a v-if="update" @click="resetPassword(record)">重置密码</a>
                </template>
              </span>
            </s-table>
          </a-col>
        </a-row>
        <a-row v-show="staffInfo.hasOwnProperty('entryDate') && info">
          <a-col
            :md="24"
            :sm="24">
            <a-descriptions title="员工信息">
              <a-descriptions-item label="入职日期">
                {{ staffInfo.entryDate }}
              </a-descriptions-item>
              <a-descriptions-item label="姓名">
                {{ staffInfo.name }}
              </a-descriptions-item>
              <a-descriptions-item label="性别">
                {{ staffInfo.sex === 0 ? '男' : '女' }}
              </a-descriptions-item>
              <a-descriptions-item label="部门">
                {{ staffInfo.department }}
              </a-descriptions-item>
              <!-- todo id map  -->
              <a-descriptions-item label="账号">
                {{ staffInfo.username }}
              </a-descriptions-item>
              <a-descriptions-item label="角色">
                {{ staffInfo.department }}
              </a-descriptions-item>
              <a-descriptions-item label="岗位">
                {{ staffInfo.jobs }}
              </a-descriptions-item>
              <a-descriptions-item label="联系方式">
                {{ staffInfo.contactWay }}
              </a-descriptions-item>
              <a-descriptions-item label="身份证号">
                {{ staffInfo.idCard }}
              </a-descriptions-item>
              <a-descriptions-item label="出生日期">
                {{ staffInfo.birthDate }}
              </a-descriptions-item>
              <a-descriptions-item label="紧急联系人">
                {{ staffInfo.emergencyContact }}
              </a-descriptions-item>
              <a-descriptions-item label="紧急联系人方式">
                {{ staffInfo.emergencyContactWay }}
              </a-descriptions-item>
              <a-descriptions-item label="配偶姓名">
                {{ staffInfo.spouseName }}
              </a-descriptions-item>
              <a-descriptions-item label="配偶联系方式">
                {{ staffInfo.spouseContactWay }}
              </a-descriptions-item>
              <a-descriptions-item label="父亲姓名">
                {{ staffInfo.fatherName }}
              </a-descriptions-item>
              <a-descriptions-item label="父亲联系方式">
                {{ staffInfo.fatherNameContactWay }}
              </a-descriptions-item>
              <a-descriptions-item label="母亲姓名">
                {{ staffInfo.motherName }}
              </a-descriptions-item>
              <a-descriptions-item label="母亲联系方式">
                {{ staffInfo.motherContactWay }}
              </a-descriptions-item>
              <a-descriptions-item label="兴趣爱好">
                {{ staffInfo.hobbies }}
              </a-descriptions-item>
              <a-descriptions-item label="备注">
                {{ staffInfo.note }}
              </a-descriptions-item>
            </a-descriptions>
          </a-col>
        </a-row>
      </div>
      <create-form
        ref="createModal"
        :visible="isAdd"
        :roloIdMap="roloIdMap"
        :loading="confirmLoading"
        @cancel="handleCancel"
        @ok="handleOk" />
      <edit-form
        ref="editModal"
        :roloIdMap="roloIdMap"
        :visible="isEdit"
        :loading="confirmLoading"
        :model="mdl"
        :footer="info && update"
        @cancel="handleCancel"
        @ok="handleOk" />
      <!-- <step-by-step-modal
        ref="modal"
        @ok="handleOk" /> -->
    </a-card>
  </page-header-wrapper>
</template>

<script>
import { STable, Ellipsis } from '@/components'
import { getstaffInfo, getStafflist, addStaff, roleSelect, updateStaff, disableStaff, resetPassword } from '@/api/manage'
import CreateForm from './modules/CreateForm'
import EditForm from './modules/EditForm'
import { message, Modal } from 'ant-design-vue'
import { mapGetters } from 'vuex'
import { isInMenu } from '../config'
import zhCN from 'ant-design-vue/es/locale/zh_CN'
// import store from '@/store'

const columns = [
  {
    title: '#',
    scopedSlots: { customRender: 'serial' }
  },
  {
    title: '入职日期',
    dataIndex: 'entryDate',
    scopedSlots: { customRender: 'entryDate' }
  },
  {
    title: '姓名',
    dataIndex: 'name'
  },
  {
    title: '部门',
    dataIndex: 'department'
  },
  {
    title: '岗位',
    dataIndex: 'jobs'
  },
  {
    title: '操作',
    dataIndex: 'action',
    width: '250px',
    scopedSlots: { customRender: 'action' }
  }
]

export default {
  name: 'TableList',
  components: {
    STable,
    Ellipsis,
    CreateForm,
    EditForm
  },
  data () {
    this.columns = columns
    return {
      locale: zhCN,
      // 权限参数
      info: false, // 配置的dialogue
      list: false, // 查
      save: false, // 删
      select: false, // 查
      status: false, // 禁用
      update: false,
      // create model
      isAdd: false,
      confirmLoading: false,
      mdl: null,
      roloIdMap: undefined,
      // 高级搜索 展开/关闭
      advanced: false,
      isEdit: false,
      isDepart: false,
      // 查询参数
      queryParam: {},
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        // const requestParameters = Object.assign({}, parameter, this.queryParam)
        const requestParameters = { page: parameter.pageNo, limit: parameter.pageSize }
        // console.log('loadData request parameters:', requestParameters)
        const param = Object.assign({}, this.queryParam)
        if (this.queryParam.entryDate) {
          param.entryBeginDate = this.queryParam.entryDate[0]
          param.entryEndDate = this.queryParam.entryDate[1]
        }
        return getStafflist(Object.assign({}, param, requestParameters, { entryDate: undefined })).then(res => {
          return Object.assign({}, res, {
            totalCount: res.total,
            pageNo: parameter.pageNo,
            pageSize: parameter.pageSize
          })
        })
      },
      staffInfo: {},
      selectedRowKeys: [],
      selectedRows: [],
      physicalSurveyCurrRowId: null
    }
  },
  filters: {},
  created () {},
  mounted () {
    this.info = isInMenu(this.menu, 'ROLE_but:user:info')
    this.list = isInMenu(this.menu, 'ROLE_but:user:list')
    this.save = isInMenu(this.menu, 'ROLE_but:user:save')
    this.select = isInMenu(this.menu, 'ROLE_but:user:select')
    this.status = isInMenu(this.menu, 'ROLE_but:user:status')
    this.update = isInMenu(this.menu, 'ROLE_but:user:update')
    roleSelect().then(res => {
      this.roloIdMap = res.data
    })
  },
  computed: {
    ...mapGetters(['menu']),
    rowSelection () {
      return {
        selectedRowKeys: this.selectedRowKeys,
        onChange: this.onSelectChange
      }
    }
  },
  methods: {
    searchStaff () {
      const param = Object.assign({}, this.queryParam)
      if (this.queryParam.entryDate) {
        param.entryBeginDate = this.queryParam.entryDate[0]
        param.entryEndDate = this.queryParam.entryDate[1]
      }
      param.entryDate = undefined
      this.$refs.table.refresh()
    },
    handleAdd () {
      this.mdl = null
      this.isAdd = true
    },
    handleEdit (record) {
      this.mdl = { ...record }
      getstaffInfo(record.userId).then(res => {
        this.isEdit = true
        // if (res.data.workStatus === 4) {
        //   this.isDepart = true
        // }
        const form = this.$refs.editModal.form
        this.$refs.editModal.statusChange(res.data.workStatus)
        this.$nextTick(() => {
          form.setFieldsValue(res.data)
        })
      })
    },
    handleOk () {
      const form = this.isAdd ? this.$refs.createModal.form : this.$refs.editModal.form
      this.confirmLoading = true
      form.validateFields((errors, values) => {
        if (!errors) {
          if (this.isAdd) {
            // 新增
            addStaff(
              Object.assign({}, values, {
                status: 1,
                roleIdList: undefined,
                roleIds: String(values.roleIdList.join(','))
              })
            ).then(res => {
              if (res.code === 0) {
                this.isAdd = false
                form.resetFields()
                this.$refs.table.refresh()
                this.$message.info('新增成功')
              }
            }).finally(() => {
              this.confirmLoading = false
            })
          } else if (this.isEdit) {
            const userId = this.mdl.userId
            // todo roleIdList 不为空
            // const roleIdList = this.mdl.roleIdList
            const roleIdList = values.roleIdList.map(item => item)
            const param = Object.assign({}, values, {
              userId,
              roleIds: String(roleIdList.join(',')),
              roleIdList: undefined
            })
            updateStaff(param).then(() => {
              this.isEdit = false
              this.confirmLoading = false
              form.resetFields()
              this.$refs.table.refresh()
              this.$message.info('修改成功')
            }).finally(() => {
              this.confirmLoading = false
            })
          }
        } else {
          this.confirmLoading = false
        }
      })
    },
    handleCancel () {
      this.isAdd = false
      this.isEdit = false

      const form = this.$refs.createModal.form
      form.resetFields() // 清理表单数据（可不做）
      this.$refs.editModal.form.resetFields()
    },
    deleteUser (userId) {
      disableStaff({ userId, status: 0 }).then(res => {
        message.success('禁用成功')
        this.$refs.table.refresh()
      })
    },
    startUser (userId) {
      disableStaff({ userId, status: 1 }).then(res => {
        message.success('启用成功')
        this.$refs.table.refresh()
      })
    },
    onSelectChange (selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
    },
    tableCustomRow (record, index) {
      return {
        style: {
          'background-color': record.userId === this.physicalSurveyCurrRowId ? '#dff3fe' : 'white'
        },
        on: {
          click: event => {
            this.physicalSurveyCurrRowId = record.userId
            this.staffInfo = record
          }
        }
      }
    },
    resetPassword (record) {
      Modal.confirm({
        title: '重置密码',
        content: '密码将重置为auZar123',
        onOk: () => {
          resetPassword({
            userId: record.userId,
            password: 'auZar123'
          }).then(() => {
            this.$message.success('密码重置成功')
          })
        }
      })
    }
  }
}
</script>
